package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:ahang
 * @create:2022-08-02 21:05
 * @Description:根据username从数据库中查询admin信息
 */
@Component
public class MyUserDetailsService implements UserDetailsService {
    @Reference
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username获取admin对象
        Admin admin = adminService.getByUsername(username);

        if(admin == null){//用户名错误,查询失败
            throw new UsernameNotFoundException("用户名错误");
        }else{//用户名正确,判断密码正确,不需要开发者比较
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("admin_add"));
            authorities.add(new SimpleGrantedAuthority("role_update"));
            //authorities用户登录成功后授予指定的权限
            return new User(username,admin.getPassword(),authorities);
        }
    }
}
